package com.example.demo.service.impl;


import com.example.demo.dao.OrderDao;
import com.example.demo.pojo.Order;
import com.example.demo.service.OrderService;
import com.google.common.base.Strings;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author BeauFang
 * Date: 2020/8/13
 */
@Service
public class OrderServiceImpl implements OrderService {

    private static final String SECKILL_PHONE_TOPIC = "seckill_phone_topic";
    private static final String REDIS_REMAIN_COUNT_KEY = "phone:remain:count";

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean checkInventory() {
        String s = redisTemplate.opsForValue().get(REDIS_REMAIN_COUNT_KEY);
        return !Strings.isNullOrEmpty(s) && Integer.parseInt(s) > 0;
    }

    /**
     * 扣减库存，将订单发送到 mq
     *
     * @param order
     */
    @Override
    public void submit(Order order) {
        redisTemplate.opsForValue().increment(REDIS_REMAIN_COUNT_KEY, -1);
        rocketMQTemplate.convertAndSend(SECKILL_PHONE_TOPIC, order);
    }

    @Override
    public List<Order> findAll() {
        return orderDao.findAll();
    }

    @Override
    public Order findById(String id) {
        return orderDao.findById(id).get();
    }

    @Override
    public void save(Order order) {
        orderDao.save(order);
    }

    /**
     * 将过期的订单修改为 cancel
     *
     * @return
     */
    @Override

    public int updateOrderState(long time) {
        return orderDao.updateOrderState(time);
    }

    @Override
    public void initInventory() {
        // 初始库存写死
        redisTemplate.opsForValue().set(REDIS_REMAIN_COUNT_KEY, "10");
    }


}
